import type { UserInfo } from '/#/store';
import type { ErrorMessageMode } from '/#/axios';
import { defineStore } from 'pinia';
import { store } from '@/store';
import { PageEnum } from '@/enums/pageEnum';
import {
  ROLES_KEY,
  TOKEN_KEY,
  USER_INFO_KEY,
  USER_ORGS_KEY,
  USER_ORG_KEY,
} from '@/enums/cacheEnum';
import { getAuthCache, setAuthCache } from '@/utils/auth';
import { GetUserInfoModel, LoginParams } from '@/api/sys/model/userModel';
import { doLogout, getUserInfo, loginApi } from '@/api/sys/user';
import { useI18n } from '@/hooks/web/useI18n';
import { useMessage } from '@/hooks/web/useMessage';
import { router } from '@/router';
import { usePermissionStore } from '@/store/modules/permission';
import { RouteRecordRaw } from 'vue-router';
import { PAGE_NOT_FOUND_ROUTE } from '@/router/routes/basic';
import { isArray } from '@/utils/is';
import { refreshCache } from '@/utils/cache/busCache';
import { useWatermark } from '@/hooks/web/useWatermark';
import { h } from 'vue';
import setting from '@/settings/projectSetting';
import headerImg from '@/assets/images/header.jpg';

interface UserState {
  userInfo: Nullable<UserInfo>;
  token?: string;
  // roleList: RoleEnum[];
  sessionTimeout?: boolean;
  lastUpdateTime: number;
  // 当前选择的组织
  currentOrg?: string;
  orgs: Recordable[];
  roles: Recordable[];
}

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): UserState => ({
    // user info
    userInfo: null,
    // token
    token: undefined,
    // roleList
    roles: [],
    // Whether the login expired
    sessionTimeout: false,
    // Last fetch time
    lastUpdateTime: 0,
    currentOrg: undefined,
    orgs: [],
  }),
  getters: {
    getUserInfo(state): UserInfo {
      return state.userInfo || getAuthCache<UserInfo>(USER_INFO_KEY) || {};
    },
    getToken(state): string {
      return state.token || getAuthCache<string>(TOKEN_KEY);
    },
    getRoles(state): Recordable[] {
      return state.roles.length > 0 ? state.roles : getAuthCache(ROLES_KEY);
    },
    getOrgs(state): Recordable[] {
      return state.orgs.length > 0 ? state.orgs : getAuthCache(USER_ORGS_KEY);
    },
    getSessionTimeout(state): boolean {
      return !!state.sessionTimeout;
    },
    getLastUpdateTime(state): number {
      return state.lastUpdateTime;
    },
    getCurrentOrg(state): string {
      return state.currentOrg || getAuthCache<string>(USER_ORG_KEY);
    },
  },
  actions: {
    setToken(info: string | undefined) {
      this.token = info ? info : ''; // for null or undefined value
      setAuthCache(TOKEN_KEY, info);
    },
    setRoles(roles: Recordable[]) {
      this.roles = roles;
      setAuthCache(ROLES_KEY, roles);
    },
    setOrgs(orgs: Recordable[]) {
      this.orgs = orgs;
      setAuthCache(USER_ORGS_KEY, orgs);
    },
    setUserInfo(info: UserInfo | null) {
      this.userInfo = info;
      this.lastUpdateTime = new Date().getTime();
      const permissionStore = usePermissionStore();
      permissionStore.setPermCodeList(this.userInfo?.permissions || []);
      setAuthCache(USER_INFO_KEY, info);
    },
    setCurrentOrg(org: string) {
      // 
      this.currentOrg = org;
      setAuthCache(USER_ORG_KEY, org);
    },
    setSessionTimeout(flag: boolean) {
      this.sessionTimeout = flag;
    },
    resetState() {
      this.userInfo = null;
      this.token = '';
      this.roles = [];
      this.sessionTimeout = false;
    },
    /**
     * @description: login
     */
    async login(
      params: LoginParams & {
        goHome?: boolean;
        mode?: ErrorMessageMode;
      }
    ): Promise<GetUserInfoModel | null> {
      try {
        const { goHome = true, mode, ...loginParams } = params;
        // const data = await loginApi(loginParams, mode);
        // const { token } = data;
        const token = await loginApi(loginParams, mode);
        // save token
        this.setToken(token);
        return this.afterLoginAction(goHome);
      } catch (error) {
        return Promise.reject(error);
      }
    },
    async afterLoginAction(goHome?: boolean): Promise<GetUserInfoModel | null> {
      if (!this.getToken) return null;
      // 初始化字典
      // refreshCache();

      // get user info
      const userInfo = await this.getUserInfoAction();
      // debugger
      // const sessionTimeout = this.sessionTimeout;
      // if (sessionTimeout) {
      //   this.setSessionTimeout(false);
      // } else {
      //   const permissionStore = usePermissionStore();
      //   if (!permissionStore.isDynamicAddedRoute) {
      //     const routes = await permissionStore.buildRoutesAction();
      //     routes?.forEach((route) => {
      //       router.addRoute(route as unknown as RouteRecordRaw);
      //     });
      //     router.addRoute(PAGE_NOT_FOUND_ROUTE as unknown as RouteRecordRaw);
      //     permissionStore.setDynamicAddedRoute(true);
      //   }
      //   permissionStore.setPermCodeList(userInfo?.permissions || []);
      //   goHome &&
      //     (await router.replace(userInfo?.welcomeRoute || PageEnum.BASE_HOME));
      // }
      await router.replace(PageEnum.BASE_HOME)
      return userInfo;
    },
    async getUserInfoAction(): Promise<UserInfo | null> {
      if (!this.getToken) return null;
      const userInfo = await getUserInfo();
      // const { roles = [] } = userInfo;
      userInfo.avatar =
        `${setting.fileUrl}/preview/${userInfo.avatar}` || headerImg;
      // this.setOrgs(userInfo.orgs);
      // if (isArray(roles)) {
      //   this.setRoles(roles);
      // } else {
      //   userInfo.roles = [];
      //   this.setRoles([]);
      // }
      this.setUserInfo(userInfo);
       
      if (setting.showWaterMarker) {
        // 添加水印
        const { setWatermark } = useWatermark();
        setWatermark(userInfo?.username);
      }
      return userInfo;
    },
    /**
     * @description: logout
     */
    async logout(goLogin = false) {
      if (this.getToken) {
        try {
          await doLogout();
        } catch {
          console.log('注销Token失败');
        }
      }
      // this.setToken(undefined);
      // this.setSessionTimeout(false);
      // this.setUserInfo(null);
      // goLogin && router.push(PageEnum.BASE_LOGIN);
      this.frontLogout(goLogin);
    },
    frontLogout(goLogin) {
      this.setToken(undefined);
      this.setSessionTimeout(false);
      this.setUserInfo(null);
      goLogin && router.push(PageEnum.BASE_LOGIN);
    },
    /**
     * @description: Confirm before logging out
     */
    confirmLoginOut() {
      const { createConfirm } = useMessage();
      const { t } = useI18n();
      createConfirm({
        iconType: 'warning',
        title: () => h('span', t('sys.app.logoutTip')),
        content: () => h('span', t('sys.app.logoutMessage')),
        onOk: async () => {
          await this.logout(true);
        },
      });
    },
  },
});

// Need to be used outside the setup
export function useUserStoreWithOut() {
  return useUserStore(store);
}
